<template>
  <HeadContainer :title="$t('title.prefer')" @back="back">
    <form class="gap-col-16">
      <GenderPicker
        v-model="genderPicker.value"
        :err-msg="parseError(genderPicker.error)"
        :gender="userData.gender"
        :interestedIn="interestedValues"
      ></GenderPicker>
      <v-divider></v-divider>
      <div class="mt-4">
        <div class="d-flex gap-row-16">
          <div @click="onSave()" class="primary-btn w-100 d-flex justify-center align-center">
            {{ $t('common.save') }}
          </div>
        </div>
      </div>
      <div
        v-if="setGenderErrMsg"
        class="text-start err-msg font-size-14 font-weight-400 line-height-120 text-primary-x"
      >
        {{ setGenderErrMsg }}
      </div>
    </form>
  </HeadContainer>
</template>

<script setup>
import { join } from 'lodash-es'
import { reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useNavStore } from '@/store/nav'
import { usePopupMessageStore } from '@/store/popup-message'
import { $t } from '@/i18n'
import { parseError, useYup } from '@/plugins/yup'
import GenderPicker from '@/components/form/GenderPicker.vue'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import { NAVS } from '@/constant'
import API from '@/http'

const emits = defineEmits(['toPage'])

function back() {
  emits('toPage', 2, 'settings')
}

const accountStore = useAccountStore()
const { setUserData } = accountStore
const { open } = usePopupMessageStore()
const { userData } = storeToRefs(accountStore)
const navStore = useNavStore()
const { refreshNavs } = navStore

const genderPicker = reactive({
  value: '',
  error: '',
})

const valueString = userData.value.interested_in
const interestedValues = valueString.split(',').map(Number)

const setGenderErrMsg = ref('')

const yup = useYup()
const schema = yup.object({
  gender: yup.number().required(),
  interestedIn: yup.array().min(1),
})

const onSave = () => {
  schema
    .validate(genderPicker.value)
    .then((n) => {
      genderPicker.error = ''

      API.Auth.fondness({
        data: {
          gender: genderPicker.value.gender,
          interested_in: join(genderPicker.value.interestedIn, ','),
        },
      })

        .then((response) => {
          userData.value.interested_in = join(genderPicker.value.interestedIn, ',')
          console.log('後端傳送成功', response)

          open($t('common.setSuc'))
          emits('toPage', 2, 'settings')

          refreshNavs([NAVS.HOME, NAVS.SEARCH])
        })
        .catch((err) => {
          console.error('就是沒傳到後端啦', err)
          setGenderErrMsg.value = err.message
        })
      console.log('前端傳送成功', n)
    })
    .catch((error) => {
      genderPicker.error = error
    })
}
</script>
